package com.jpatest.demo.Redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jpatest.demo.entity.User;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;

public class MyRedisChannelListener implements MessageListener {
    TwoLevelCacheManager cacheManager;

    public void setCacheManager(TwoLevelCacheManager cacheManager){
        this.cacheManager = cacheManager;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] msg_b = message.getBody();
        try{
            JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
            String jsonString = (String)jdkSerializationRedisSerializer.deserialize(msg_b);
            JSONObject json = (JSONObject)JSON.parseObject(jsonString);
            json.put("key",Long.parseLong(json.get("key").toString()));
            if(json==null){
                System.out.println("Redis更新或删除指令获取失败！");
            }else{
                cacheManager.receiver(json);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
